﻿using Ec.NETCoreFramework.Common.Core;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Ec.NETCoreFramework.Common.MQ;
using Ec.NETCoreFramework.Common.Core.Utilities;
using Ec.NETCoreFramework.Common.Core.Serializer;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Threading;
using System.Diagnostics;
using Ec.NETCoreFramework.Common.Plug.Core;
using Ec.NETCoreFramework.Common.Clients;
using System.Linq;

namespace MQ_Approval
{
    /// <summary>
    /// 汇报
    /// </summary>
    public class TimingSyncApproval : ApprovalSync
    {
        private string logTitle = "TimingSyncApproval";
        private RequestAppSecret _appSecret;
        private string _SoftwareVersion = string.Empty;

        public TimingSyncApproval(RequestAppSecret appSecret, ConsumeConfig consumeConfig) : base(appSecret, consumeConfig)
        {
            _appSecret = appSecret;
            _SoftwareVersion = AppsettingsHelper.app(new string[] { "SoftwareVersion" });
            _consumeConfig = consumeConfig;
        }
        /// <summary>
        /// 执行入口
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public override async Task Excute(Dictionary<string, object> dic)
        {
            var limit = 500;
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                while (true)
                {
                    //从业务系统拉数据
                    var list = await PullData(limit);
                    if (list == null || list.Count == 0)
                    {
                        Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}】没有拉取到数据哟");
                        break;
                    }
                    //从微信拉数据并同步到业务系统
                    await TimingSync(list);

                    if (list.Count < limit)
                    {
                        Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}-{_SoftwareVersion}】此次执行结束，耗时{stopwatch.ElapsedMilliseconds}ms");
                        break;
                    }
                    Thread.Sleep(1000);
                }
                stopwatch.Stop();
            }
            catch (Exception ex)
            {

                if (stopwatch.IsRunning)
                {
                    stopwatch.Stop();
                }
                Console.WriteLine($"【{_consumeConfig.Domain}-{logTitle}】:{ex.Message}");
            }
        }

        /// <summary>
        /// 从业务系统拉数据
        /// </summary>
        /// <returns></returns>
        private async Task<List<ApprovalOutput>> PullData(int limit)
        {
            var dic = new Dictionary<string, object>()
            {
                {"limit",limit.ToString() }
            };
            var result = await new ApiRequestClient(_appSecret).
                GetResponse<List<ApprovalOutput>>(_consumeConfig.Domain,
                "wxgroup.oa.approval.lasttime.get", dic);
            if (result.Success)
            {
                var ret = (IResponse<List<ApprovalOutput>>)result;
                return (ret.Content);
            }
            return null;

        }
        /// <summary>
        /// 定时同步
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private async Task TimingSync(List<ApprovalOutput> list)
        {
            foreach (var item in list)
            {
                var dt_month_start = item.date_time == 0 ? DateTime.Now.AddDays(-3) : Utils.UnixTimeToTime(item.date_time.ToString(), 10);

                var end = 0L;

                while (DateTime.Now > dt_month_start)
                {
                    var begin = Utils.ToUnixTime(dt_month_start, 10);

                    //15天
                    var dt_month_end = dt_month_start.AddDays(15);

                    //结束时间一天大于当前时间时
                    if (dt_month_end > DateTime.Now)
                    {

                        end = Utils.ToUnixTime(DateTime.Now, 10);
                    }
                    else
                    {
                        end = Utils.ToUnixTime(dt_month_end, 10);
                    }
                    //获取汇报列表
                    await GetApprovalList(item, begin, end, "0");
                    //获取汇报详情
                    await GetApprovalDetail(item);
                    //将最后时间赋值给开始时间
                    dt_month_start = dt_month_end;
                }

                await UpdateEndTime(item, end);


            }

        }
       
        /// <summary>
        /// 更新最后执行时间
        /// </summary>
        /// <param name="item"></param>
        /// <param name="end_time"></param>
        /// <returns></returns>
        private async Task UpdateEndTime(ApprovalOutput item, long end_time)
        {
            var dic = new Dictionary<string, object>()
                {
                    {"id",item.id },
                    {"lastsynctime",end_time }
                };
            var result = await new ApiRequestClient(_appSecret).
        PostBinary<JObject>(_consumeConfig.Domain,
        "wxgroup.oa.Approval.lasttime.sync", dic);
            if (!result.Success)
            {
                Console.WriteLine($"【{logTitle}】:{result.Message};{dic.ToLinkString()}");
            }

        }
    }
}
